<template>
  <div class="m-page">
    <m-header title="仓库看板"></m-header>
    <div class="m-body">
      <m-row :gutter="20" class="first-floor">
        <m-col :span="24 / totals.length" v-for="t in totals" :key="t.color">
          <m-num-board :color="t.color" :title="t.title" :number="t.number" />
        </m-col>
      </m-row>

      <m-row :gutter="20" class="second-floor">
        <m-col :span="12">
          <m-box title="进出库明细">
            <m-scroll-board
              :row-num="6"
              :loading="inoutWarehouseDetailLoading"
              :cols="inoutWarehouseDetailCols"
              :datas="inoutWarehouseDetailData"
            />
          </m-box>
        </m-col>
        <m-col :span="12">
          <m-box title="待发料清单">
            <m-scroll-board
              :row-num="6"
              :loading="listOfMaterialsToBeIssuedLoading"
              :cols="listOfMaterialsToBeIssuedCols"
              :datas="listOfMaterialsToBeIssuedData"
            />
          </m-box>
        </m-col>
      </m-row>
      <m-row :gutter="20" class="third-floor">
        <m-col :span="12">
          <m-box title="库存TOP10预警">
            <top10Echart :loading="top10Loading" :labels="top10Labels" :data="top10Data" />
          </m-box>
        </m-col>
        <m-col :span="12">
          <m-box title="来料检验进度">
            <m-scroll-board
              :row-num="6"
              :loading="progressOfIncomingInspectionLoading"
              :cols="progressOfIncomingInspectionCols"
              :datas="progressOfIncomingInspectionData"
            />
          </m-box>
        </m-col>
      </m-row>
    </div>
  </div>
</template>

<script setup>
// 业务组件
import top10Echart from '@/views/WarehouseBoard/components/top10Echart/index.vue'
// 其他方法
import http from '@/utils/request'
import { randomColor } from '@/utils/tools'
// vue提供的api
import { ref, onBeforeMount } from 'vue'

const totals = ref([
  /*
   * 来料入库数：当日收货入库已完成的单据数=====>采购入库PPR
   * 生产入库数：当日完工入库的单据数=====>成品完工入库MI
   * 生产领料数：当日生产领料的单据数=====>生产领料MO
   * 销售出库数：当日销售出库的单据数=====>移除此需求
   * 杂项出入库：当日杂项出入库的单据数===>杂项入库OI、杂项出库OO
   * 查询所有已完成交接的出入库单据明细（包括以上5种单据）
   */
  // Math.ceil(Math.random() * 1000000)
  { color: '#FFF8DC', title: '来料入库数', code: 'PPR', number: 0 },
  { color: '#7FFF00', title: '生产入库数', code: 'MI', number: 0 },
  { color: '#00FFFF', title: '生产领料数', code: 'MO', number: 0 },
  // { color: '#00BFFF', title: '销售出库数', code: 'PPR', number: 0 },
  { color: '#BA55D3', title: '杂项入库数', code: 'OI', number: 0 },
  { color: '#FF7F50', title: '杂项出库数', code: 'OO', number: 0 }
])

// 进出库明细
const inoutWarehouseDetailCols = ref([
  { width: 40, title: '序号', type: 'seq', align: 'center' },
  { width: 120, title: '仓库', property: 'WAREHOUSE_CODE' },
  { width: 120, title: '货位', property: 'LOC_CODE' },
  { width: 130, title: '类型', property: 'MITEM_CATEGORY_CODE' },
  { width: 150, title: '物料编码', property: 'MITEM_CODE' },
  { width: 150, title: '物料名称', property: 'MITEM_NAME' },
  { width: 80, title: '数量', property: 'PICK_QTY' },
  { width: 80, title: '单位', property: 'UOM' },
  { width: 140, title: '规格型号', property: 'SPECIFICATION' }
])
const inoutWarehouseDetailData = ref([])
const inoutWarehouseDetailLoading = ref(false)

// 待发料清单
const listOfMaterialsToBeIssuedCols = ref([
  { width: 40, title: '序号', type: 'seq', align: 'center' },
  { width: 150, title: '单据号', property: 'BILL_NO' },
  { width: 150, title: '物料编码', property: 'MITEM_CODE' },
  { width: 150, title: '物料名称', property: 'MITEM_NAME' },
  { width: 150, title: '仓库', property: 'WAREHOUSE_CODE' },
  { width: 150, title: '货位', property: 'LOC_CODE' },
  { width: 150, title: '数量', property: 'PICK_QTY' },
  { width: 150, title: '单位', property: 'UOM' },
  { width: 150, title: '规格型号', property: 'SPECIFICATION' }
])
const listOfMaterialsToBeIssuedData = ref([])
const listOfMaterialsToBeIssuedLoading = ref(false)

// 来料检验进度
const progressOfIncomingInspectionCols = ref([
  { width: 40, title: '序号', type: 'seq', align: 'center' },
  { width: 150, title: '单据号', property: 'BILL_NO' },
  { width: 150, title: '物料编码', property: 'MITEM_CODE' },
  { width: 150, title: '物料描述', property: 'MITEM_NAME' },
  { width: 150, title: '仓库', property: 'WAREHOUSE_CODE' },
  { width: 150, title: '货位', property: 'LOC_CODE' },
  { width: 150, title: '数量', property: 'PICK_QTY' },
  {
    width: 150,
    title: '状态',
    property: '状态',
    formatter: ({ value }) => {
      return `<span style="color: ${randomColor()}">${value}</span>`
    }
  }
])
const progressOfIncomingInspectionData = ref([])
const progressOfIncomingInspectionLoading = ref(false)

// 库存TOP10预警
const top10Loading = ref(false)
const top10Labels = ref(Array.from({ length: 10 }).map((_, i) => `物料${i + 1}`))
const top10Data = ref(Array.from({ length: 10 }).map((_, i) => 0))

// 系统参数【选项】
const getSystemParams = async function (groupcode) {
  let options = []
  try {
    const res = await http.get('/mes/param/getbygroupcode', { groupcode })
    options = res.map((r) => {
      return { ...r, label: r.PARAM_ALIAS, value: r.PARAM_CODE }
    })
  } catch (e) {
    this.$message.error(e.message || e.statusText)
    console.error(e)
  } finally {
    return options
  }
}

// // 模拟接口请求，延迟1秒返回数据
// function getData(len, cols) {
//   return new Promise((resolve, reject) => {
//     setTimeout(() => {
//       const res = Array.from({ length: len }).map((r, i) => {
//         const idx = i + 1
//         const newRow = cols.reduce((res, _) => {
//           if (_.type !== 'seq') {
//             res[_.property] = _.title + idx
//           }
//           return res
//         }, {})
//         return newRow
//       })
//       resolve(res)
//     }, 1000)
//   })
// }

// function initMock() {
//   // 获取 进出库明细 数据
//   inoutWarehouseDetailLoading.value = true
//   getData(24, inoutWarehouseDetailCols.value)
//     .then((res1) => {
//       inoutWarehouseDetailData.value = res1
//     })
//     .finally(() => {
//       inoutWarehouseDetailLoading.value = false
//     })
//   // 获取 待发料清单 数据
//   listOfMaterialsToBeIssuedLoading.value = true
//   getData(24, listOfMaterialsToBeIssuedCols.value)
//     .then((res2) => {
//       listOfMaterialsToBeIssuedData.value = res2
//     })
//     .finally(() => {
//       listOfMaterialsToBeIssuedLoading.value = false
//     })
//   // 获取 来料检验进度 数据
//   progressOfIncomingInspectionLoading.value = true
//   getData(24, progressOfIncomingInspectionCols.value)
//     .then((res3) => {
//       progressOfIncomingInspectionData.value = res3
//     })
//     .finally(() => {
//       progressOfIncomingInspectionLoading.value = false
//     })
// }

// 汇总
async function getWHBillReport(dateTime) {
  try {
    const t = await http.get('/v1/kanban/getWHBillReport', { dateTime })
    totals.value = totals.value.map((r) => {
      const opt = t.find((_) => _.BUSINESS_CATEGORY_CODE === r.code)
      r.number = opt?.count || 0
      return r
    })
  } catch (e) {
    console.error(e)
  }
}
// 进出库明细
async function getWHBillDetailReport(dateTime) {
  try {
    const data = await http.get('/v1/kanban/getWHBillDetailReport', { dateTime })
    console.log('进出库明细', data)
    inoutWarehouseDetailData.value = data
  } catch (e) {
    console.error(e)
  } finally {
    inoutWarehouseDetailLoading.value = false
  }
}
// 待发料清单
async function GetWHBillPendingMaterialsDetailReport(dateTime) {
  listOfMaterialsToBeIssuedLoading.value = true
  try {
    const data = await http.get('/v1/kanban/GetWHBillPendingMaterialsDetailReport', {
      dateTime
    })
    console.log('待发料清单', data)
    listOfMaterialsToBeIssuedData.value = data
  } catch (e) {
    console.error(e)
  } finally {
    listOfMaterialsToBeIssuedLoading.value = false
  }
}
// 库存TOP10预警
async function getWHReport(dateTime) {
  top10Loading.value = true
  try {
    const data = await http.get('/v1/kanban/getWHReport')
    // console.log('库存TOP10预警', data)
    const list = data.sort((a, b) => {
      return b.QTY - a.QTY
    })
    // .slice(0, 10)
    // .map((r) => {
    //   return { MITEM_CODE: r.MITEM_CODE, QTY: r.QTY }
    // })
    top10Labels.value = []
    top10Data.value = []
    list.forEach((r) => {
      top10Labels.value.push(r.MITEM_NAME || r.MITEM_CODE)
      top10Data.value.push(r.QTY)
    })
    console.log('库存TOP10预警', list, top10Labels, top10Data)
  } catch (e) {
    console.error(e)
  } finally {
    top10Loading.value = false
  }
}
// 来料检验进度
async function getWHBillReceivingOfIncomingMaterialsReport(dateTime) {
  progressOfIncomingInspectionLoading.value = true
  try {
    const data = await http.get('/v1/kanban/getWHBillReceivingOfIncomingMaterialsReport', {
      dateTime
    })
    console.log('来料检验进度', data)
    progressOfIncomingInspectionData.value = data
  } catch (e) {
    console.error(e)
  } finally {
    progressOfIncomingInspectionLoading.value = false
  }
}

async function init() {
  if (location.origin.indexOf('localhost') > -1 || location.origin.indexOf('127.0.0.1') > -1) {
    getWHBillReport('2024-06-21')
    getWHBillDetailReport('2024-08-29')
    GetWHBillPendingMaterialsDetailReport()
    getWHReport()
    getWHBillReceivingOfIncomingMaterialsReport('2024-08-13')
  } else {
    getWHBillReport()
    getWHBillDetailReport()
    GetWHBillPendingMaterialsDetailReport()
    getWHReport()
    getWHBillReceivingOfIncomingMaterialsReport()
  }
}

let timeId = null
onBeforeMount(async () => {
  init()
  timeId = setInterval(
    () => {
      init()
    },
    1000 * 60 * 10
  )
})

onBeforeUnmount(async () => {
  clearInterval(timeId)
})
</script>
<style lang="less" scoped>
.m-page {
  .m-body {
    .m-row {
      margin-bottom: 0;
      &.first-floor {
        height: 140px;
        .m-col {
          height: 100%;
          position: relative;
          .m-num-board {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
      &.second-floor,
      &.third-floor {
        height: calc((100% - 140px) / 2);
        .m-col {
          height: 100%;
        }
      }
    }
  }
}
</style>
